package com.dq.security.exception;

import com.dq.security.exception.common.CommonError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //捕获处理自定义异常 此类异常由程序员主动抛出

    @ExceptionHandler(value = CommonException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse doXueChengExceptionHandler(CommonException e) { //此方法捕获  XueChengNormalException异常  并报出500状态码
        //1. 可以log打印  可以统一返回前端数据
        String errMessage = e.getErrMessage();
        log.error("捕获异常信息:{}", e.getErrMessage());
        return new RestErrorResponse(errMessage);
    }


    //捕获不可预知异常  例如MYSQL connection timeOut
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse doExceptionHandler(Exception e) { //此方法捕获  XueChengNormalException异常  并报出500状态码
        //1. 可以log打印  可以统一返回前端数据
        String errMessage = e.getMessage();
        log.error("捕获异常信息:{}", e.getMessage());
        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
    }

    //针对JSR303异常捕获
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse doMethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) { //此方法捕获  XueChengNormalException异常  并报出500状态码
        //1. 可以log打印  可以统一返回前端数据
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder errorsResult = new StringBuilder();
        //遍历错误Field原因然后拼接
        fieldErrors.forEach(error -> errorsResult.append(error.getDefaultMessage()).append(","));
        return new RestErrorResponse(errorsResult.toString());
    }
}